import config from '@/common/config'

const request = (method, url, data) => {
	return new Promise((reslove, reject) => {
		const token = uni.getStorageSync('USER_TOKEN') || null;
		console.log("apiRequest:",url,token,data)
		
		uni.request({
			method,
			url: config.baseUrl + url,
			header: {
				authorization: `Bearer ${token}`
			},
			data,
			success: (res) => {
				const { code, message } = res.data 
				if (res.statusCode != 200 && res.statusCode != 201) {
					//msg(message)   
					return reject(res.data)
				} 
				reslove(res.data)
			},
			fail(err) {
				reject(err) 
			}
		})
	})
}

/**
 * 通用 API 请求方法
 * @param {string} method - 请求方法 ('GET', 'POST', 'PUT', 'DELETE' 等)
 * @param {string} url - 请求地址
 * @param {Object} params - 请求参数
 * @returns {Promise} - 返回请求结果
 */
export const apiRequest = async (method, url, params = {}) => {
	try {
		const response = await request(method, url, params);
		return response;
	} catch (error) {
		console.error(`API request failed for ${url}:`, error);
		throw error;
	}
};

// 如果需要其他通用的 API 相关方法，也可以在这里导出
export const get = (url, params) => apiRequest('GET', url, params);
export const post = (url, params) => apiRequest('POST', url, params);
export const put = (url, params) => apiRequest('PUT', url, params);
export const del = (url, params) => apiRequest('DELETE', url, params); 

export default request
